package be.android.forap.gui;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import be.android.forap.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FileExplorerActivity extends ListActivity {


	private static final String ITEM_KEY = "key";
	private static final String ITEM_IMAGE = "image";
	private static final String ROOT = "/";
	public static final String START_PATH = "START_PATH";
	public static final String RESULT_PATH = "RESULT_PATH";
	public static final String FORMAT_FILTER = "FORMAT_FILTER";
	//To read
	public static final String SELECT_ONLY_FILE_READ = "selectFileRead";
	//To save
	public static final String SELECT_ONLY_FOLDER_WRITE = "selectFolderWrite";
	
	
	private List<String> path = null;
	private TextView myPath;
	private ArrayList<HashMap<String, Object>> mList;

	private boolean selectFileRead;
	private boolean selectFolderWrite;

	private Button selectButton;

	private String parentPath;
	private String currentPath = ROOT;
	
	 private String[] formatFilter = null;
	 

	private File selectedFile;
	private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>();


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.file_explorer);
		setResult(RESULT_CANCELED, getIntent());
		Intent launcher = getIntent();
		selectFileRead = launcher.getBooleanExtra(SELECT_ONLY_FILE_READ,false);
		selectFolderWrite = launcher.getBooleanExtra(SELECT_ONLY_FOLDER_WRITE,false);
			
		String startPath = launcher.getStringExtra(START_PATH);
		formatFilter = launcher.getStringArrayExtra(FORMAT_FILTER);

		startPath = startPath != null ? startPath : ROOT;
		Log.i("STARTHPATH",startPath);
		
		
		myPath = (TextView) findViewById(R.id.fe_textview_path);

		selectButton = (Button) findViewById(R.id.fe_button_select);
		selectButton.setEnabled(selectFolderWrite);
		selectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (selectedFile != null) {
					Log.d("FE",selectedFile.getAbsolutePath());
					try {
						Log.d("FE",selectedFile.getCanonicalPath());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Log.d("FE",selectedFile.getPath());
					getIntent().putExtra(RESULT_PATH, selectedFile.getPath());
					setResult(RESULT_OK, getIntent());
					finish();
				}
			}
		});
		
		if (selectFolderWrite) {
            File file = new File(startPath);
            selectedFile = file;
            selectButton.setEnabled(true);
    }


		getDir(startPath);

	}



	private void getDir(String dirPath) {
		boolean useAutoSelection = dirPath.length() < currentPath.length();
		Integer position = lastPositions.get(parentPath);
		getDirImpl(dirPath);
		if (position != null && useAutoSelection) {
			getListView().setSelection(position);
		}
	}

	private void getDirImpl(final String dirPath) {

		currentPath = dirPath;

		final List<String> item = new ArrayList<String>();
		path = new ArrayList<String>();
		mList = new ArrayList<HashMap<String, Object>>();

		File f = new File(currentPath);
		File[] files = f.listFiles();
		if (files == null) {
			currentPath = ROOT;
			f = new File(currentPath);
			files = f.listFiles();
		}
		myPath.setText("Location: " + currentPath);

		if (!currentPath.equals(ROOT)) {
			if(!selectFolderWrite){
				item.add(ROOT);
				addItem(ROOT, R.drawable.folder);
				path.add(ROOT);
			}
			item.add("../");
			addItem("../", R.drawable.folder);
			path.add(f.getParent());
			parentPath = f.getParent();
		}

		TreeMap<String, String> dirsMap = new TreeMap<String, String>();
		TreeMap<String, String> dirsPathMap = new TreeMap<String, String>();
		TreeMap<String, String> filesMap = new TreeMap<String, String>();
		TreeMap<String, String> filesPathMap = new TreeMap<String, String>();
		for (File file : files) {
			if (file.isDirectory()) {
				String dirName = file.getName();
				dirsMap.put(dirName, dirName);
				dirsPathMap.put(dirName, file.getPath());
			} else {
				final String fileName = file.getName();
                final String fileNameLwr = fileName.toLowerCase();
                if (formatFilter != null) {
                        boolean contains = false;
                        for (int i = 0; i < formatFilter.length; i++) {
                                final String formatLwr = formatFilter[i].toLowerCase();
                                if (fileNameLwr.endsWith(formatLwr)) {
                                        contains = true;
                                        break;
                                }
                        }
                        if (contains) {
                                filesMap.put(fileName, fileName);
                                filesPathMap.put(fileName, file.getPath());
                        }
                        
                } else {
                        filesMap.put(fileName, fileName);
                        filesPathMap.put(fileName, file.getPath());
                }
			}
		}
		item.addAll(dirsMap.tailMap("").values());
		item.addAll(filesMap.tailMap("").values());
		path.addAll(dirsPathMap.tailMap("").values());
		path.addAll(filesPathMap.tailMap("").values());

		SimpleAdapter fileList = new SimpleAdapter(this, mList, R.layout.file_explorer_row, new String[] {
				ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.rowtext, R.id.rowimage });

		for (String dir : dirsMap.tailMap("").values()) {
			addItem(dir, R.drawable.folder);
		}

		for (String file : filesMap.tailMap("").values()) {
			addItem(file, R.drawable.file);
		}

		fileList.notifyDataSetChanged();

		setListAdapter(fileList);

	}

	private void addItem(String fileName, int imageId) {
		HashMap<String, Object> item = new HashMap<String, Object>();
		item.put(ITEM_KEY, fileName);
		item.put(ITEM_IMAGE, imageId);
		mList.add(item);
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {

		File file = new File(path.get(position));

		selectButton.setEnabled(false);


		if (file.isDirectory()) {
			selectButton.setEnabled(false);
			if (file.canRead()) {
				lastPositions.put(currentPath, position);
				getDir(path.get(position));
				if (selectFolderWrite) {
					selectedFile = file;
					v.setSelected(true);
					selectButton.setEnabled(true);
				}
			} else {
				new AlertDialog.Builder(this).setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "] folder can't be read!")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();
			}
		} else {
			selectButton.setEnabled(false);
			if (selectFileRead && file.canRead()) {
				selectedFile = file;
				v.setSelected(true);
				selectButton.setEnabled(true);
			} else {
				new AlertDialog.Builder(this).setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "] " + "file can't be read!")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			selectButton.setEnabled(false);
			if (!currentPath.equals(ROOT)) {
				getDir(parentPath);
			} else {
				return super.onKeyDown(keyCode, event);
			}
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	@Override
	protected void onPause() {
		String myPathStr = myPath.getText().toString();
		int idx = myPathStr.lastIndexOf(':');
		String currPath = myPathStr.substring(idx + 2);
		getIntent().putExtra(START_PATH, currPath);
		super.onPause();
	}

}

/*private static final String ITEM_KEY = "key";
	private static final String ITEM_IMAGE = "image";
	private static final String ROOT = "/";
	public static final String START_PATH = "START_PATH";
	public static final String RESULT_PATH = "RESULT_PATH";
	public static final String SELECT_FILE_READ = "selectFileRead";
	public static final String SELECT_FOLDER_WRITE = "selectFolderWrite";

	private List<String> path = null;
	private TextView myPath;
	private ArrayList<HashMap<String, Object>> mList;

	private boolean selectFileRead;
	private boolean selectFolderWrite;

	private Button selectButton;

	private String parentPath;
	private String currentPath = ROOT;

	private File selectedFile;
	private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>();


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.file_explorer);
		setResult(RESULT_CANCELED, getIntent());
		Intent launcher = getIntent();
		selectFileRead = launcher.getBooleanExtra(SELECT_FILE_READ,false);
		selectFolderWrite = launcher.getBooleanExtra(SELECT_FOLDER_WRITE,false);

		myPath = (TextView) findViewById(R.id.fe_textview_path);

		selectButton = (Button) findViewById(R.id.fe_button_select);
		selectButton.setEnabled(selectFolderWrite);
		selectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (selectedFile != null) {
					getIntent().putExtra(RESULT_PATH, selectedFile.getPath());
					setResult(RESULT_OK, getIntent());
					finish();
				}
			}
		});

		String startPath = launcher.getStringExtra(START_PATH);
		startPath = startPath != null ? startPath : ROOT;
		if (selectFolderWrite) {
            File file = new File(startPath);
            selectedFile = file;
            selectButton.setEnabled(true);
		}
		getDir(startPath);

	}



	private void getDir(String dirPath) {
		boolean useAutoSelection = dirPath.length() < currentPath.length();
		Integer position = lastPositions.get(parentPath);
		getDirImpl(dirPath);
		if (position != null && useAutoSelection) {
			getListView().setSelection(position);
		}
	}

	private void getDirImpl(final String dirPath) {

		currentPath = dirPath;

		final List<String> item = new ArrayList<String>();
		path = new ArrayList<String>();
		mList = new ArrayList<HashMap<String, Object>>();

		File f = new File(currentPath);
		File[] files = f.listFiles();
		if (files == null) {
			currentPath = ROOT;
			f = new File(currentPath);
			files = f.listFiles();
		}
		myPath.setText("Location: " + currentPath);

		if (!selectFolderWrite && !currentPath.equals(ROOT)) {
			item.add(ROOT);
			addItem(ROOT, R.drawable.folder);
			path.add(ROOT);

			item.add("../");
			addItem("../", R.drawable.folder);
			path.add(f.getParent());
			parentPath = f.getParent();
		}

		TreeMap<String, String> dirsMap = new TreeMap<String, String>();
		TreeMap<String, String> dirsPathMap = new TreeMap<String, String>();
		TreeMap<String, String> filesMap = new TreeMap<String, String>();
		TreeMap<String, String> filesPathMap = new TreeMap<String, String>();
		for (File file : files) {
			if (file.isDirectory()) {
				String dirName = file.getName();
				dirsMap.put(dirName, dirName);
				dirsPathMap.put(dirName, file.getPath());
			} else {
				final String fileName = file.getName();
				filesMap.put(fileName, fileName);
				filesPathMap.put(fileName, file.getPath());

			}
		}
		item.addAll(dirsMap.tailMap("").values());
		item.addAll(filesMap.tailMap("").values());
		path.addAll(dirsPathMap.tailMap("").values());
		path.addAll(filesPathMap.tailMap("").values());

		SimpleAdapter fileList = new SimpleAdapter(this, mList, R.layout.file_explorer_row, new String[] {
				ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.rowtext, R.id.rowimage });

		for (String dir : dirsMap.tailMap("").values()) {
			addItem(dir, R.drawable.folder);
		}

		for (String file : filesMap.tailMap("").values()) {
			addItem(file, R.drawable.file);
		}

		fileList.notifyDataSetChanged();

		setListAdapter(fileList);

	}

	private void addItem(String fileName, int imageId) {
		HashMap<String, Object> item = new HashMap<String, Object>();
		item.put(ITEM_KEY, fileName);
		item.put(ITEM_IMAGE, imageId);
		mList.add(item);
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {

		File file = new File(path.get(position));

		selectButton.setEnabled(false);


		if (file.isDirectory()) {
			selectButton.setEnabled(false);
			if (file.canRead()) {
				lastPositions.put(currentPath, position);
				getDir(path.get(position));
				if (selectFolderWrite) {
					selectedFile = file;
					v.setSelected(true);
					selectButton.setEnabled(true);
				}
			} else {
				new AlertDialog.Builder(this).setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "] folder can't be read!")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();
			}
		} else {
			selectButton.setEnabled(false);
			if (selectFileRead && file.canRead()) {
				selectedFile = file;
				v.setSelected(true);
				selectButton.setEnabled(true);
			} else {
				new AlertDialog.Builder(this).setIcon(R.drawable.icon)
				.setTitle("[" + file.getName() + "] " + "file can't be read!")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			selectButton.setEnabled(false);
			if (!currentPath.equals(ROOT)) {
				getDir(parentPath);
			} else {
				return super.onKeyDown(keyCode, event);
			}
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
*/
